<script setup lang="ts">
defineOptions({
  name: "SourceList",
  inheritAttrs: false,
});

import { SourceQuery, SourceItem } from "@/api/dict/source/types";
import { getSourceTree, deleteSource } from "@/api/dict/source";

const loading = ref(false);
const pageList = ref<SourceItem[]>([]);

const queryParams = reactive<SourceQuery>({});

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  getSourceTree(queryParams)
    .then(({ data }) => {
      pageList.value = data;
    })
    .then(() => {
      loading.value = false;
    });
}

const sourceDialogRef = ref();

// 新增事件
function openDialog(id?: number) {
  // 编辑
  if (!sourceDialogRef.value) {
    return;
  }
  sourceDialogRef.value.showDialog(id);
}

// 删除事件
function handleDelete(id: number) {
  // 提示是否删除
  ElMessageBox.confirm("此操作将永久删除该渠道, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteSource(id).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog(0)">
          <template #icon><i-ep-plus /></template>
          新增</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="pageList"
        highlight-current-row
        row-key="id"
        :expand-row-keys="['1']"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        border
      >
        <el-table-column label="渠道名称" prop="title" min-width="200" />

        <el-table-column label="排序" align="center" width="80" prop="sort" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="info">关闭</el-tag>
            <el-tag v-else type="success">使用中</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>

            <el-button
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <source-update ref="sourceDialogRef" @handleQuery="handleQuery" />
  </div>
</template>
